/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainWindow.java
 *
 * Created on 12/10/2011, 02:43:20 PM
 */

package bolsavalorappclient;


import bean.BeanAccionRemote;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.swing.DefaultListModel;
import java.util.List;
import java.util.Properties;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.TimerTask;
import java.util.Timer;


/**
 *
 * @author ari
 */
public class MainWindow extends javax.swing.JFrame {

    final boolean VENTA = true;
    final boolean COMPRA = false;
    
    private static BeanAccionRemote accion;
    private List<ConsultaWindow> consultlist;
    
    TimerTask timerTask = new TimerTask() {
        public void run() {
            refresh();
        }
    };

    /** Creates new form MainWindow */
    public MainWindow(String id, Properties properties) {

        initComponents();
        
        this.properties = properties;
        accion = lookupBeanAccionRemote(properties);
                
        this.id = id;
        consultlist = new ArrayList<ConsultaWindow>();

        jList1.setModel(new DefaultListModel());
        jList2.setModel(new DefaultListModel());
        ventaModel = (DefaultListModel) jList1.getModel();
        compraModel = (DefaultListModel) jList2.getModel();
        
        // Se obtiene toda la informacion sobre las ofertas del usuario
        // Se llenan las listas con la oferta
        try{
        compra = accion.getIdCompraInv(id);
        }catch(Exception ne){
            JOptionPane.showMessageDialog(null, "Se perdió conexión con el "
                    + "servidor", "Advertencia!!",
                    JOptionPane.INFORMATION_MESSAGE);
            new LoginWindow(properties).setVisible(true);
            this.dispose();
        }
        try{
        venta = accion.getIdVentaInv(id);
        }catch(Exception ne){
            JOptionPane.showMessageDialog(null, "Se perdió conexión con el "
                    + "servidor", "Advertencia!!",
                    JOptionPane.INFORMATION_MESSAGE); 
            new LoginWindow(properties).setVisible(true);
            this.dispose();
        }
        List<String> acciones = accion.obtenerCompraInv(id);
        for(String temp : acciones) {
            compraModel.addElement(temp);
        }
        acciones = accion.obtenerVentaInv(id);
        for(String temp : acciones) {
            ventaModel.addElement(temp);
        }
        
        this.addWindowListener(new WindowAdapter() 
        {
          public void windowClosed(WindowEvent e)
          {
            timerTask.cancel();
          }
        });
                
        /* Se coloca un timer para que se refresquen cada cierto tiempo */
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(timerTask, 0, 60 * 1000);     // Cada minuto     

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bolsa de Valores");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jPanel1.setBackground(new java.awt.Color(187, 179, 237));

        jLabel1.setText("Ofertas del usuario:");

        jLabel2.setText("Venta:");

        jLabel3.setText("Compra:");

        jList2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList2.setName("jList2"); // NOI18N
        jList2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jList2);
        jList2.getAccessibleContext().setAccessibleName("jList2");

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.setName("jList1"); // NOI18N
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);
        jList1.getAccessibleContext().setAccessibleName("jList1");

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bolsavalorappclient/arrowdowng.png"))); // NOI18N
        jLabel4.setText("jLabel4");

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bolsavalorappclient/arrowupr.png"))); // NOI18N

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bolsavalorappclient/bolsalogo.png"))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                        .addComponent(jLabel6)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(16, 16, 16)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2))))
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE))
                .addContainerGap())
        );

        jMenuBar1.setBackground(new java.awt.Color(164, 153, 238));

        jMenu1.setText("Nueva");

        jMenuItem1.setBackground(new java.awt.Color(187, 179, 237));
        jMenuItem1.setText("Venta");
        jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItem1MouseClicked(evt);
            }
        });
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setBackground(new java.awt.Color(187, 179, 237));
        jMenuItem2.setLabel("Compra");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Consultar");
        jMenu3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu3MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu3);

        jMenu2.setText("Estadisticas");
        jMenu2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu2MouseClicked(evt);
            }
        });
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        // TODO add your handling code here:

    }//GEN-LAST:event_jList1ValueChanged

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
        // TODO add your handling code here:
        //  Se crea un dialogo en el que se muestra toda la informacion
        // sobre la oferta
        if(jList1.getModel().getSize() == 0) 
            return;
        
        OfertaDialog oferta = null;
        try{
        oferta = new OfertaDialog(this, true,properties);
        }catch(Exception e){
            new LoginWindow(properties).setVisible(true);
        }
                    
        Long index = venta.get(jList1.getSelectedIndex());
        
        int num = accion.getNum(index);
        if(num == 0) {
            refresh();
            return;
        }
        
               
        // Se envia la informacion al dialogo
        oferta.setOferta(VENTA, jList1.getSelectedValue().toString(), Integer.toString(num), Double.toString(accion.getMonto(index)), index);

        oferta.setVisible(true);
    }//GEN-LAST:event_jList1MouseClicked

    private void jList2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseClicked
        // TODO add your handling code here:
        if(jList2.getModel().getSize() == 0) 
            return;
        
        OfertaDialog oferta = null;
        try{
            oferta = new OfertaDialog(this, true,properties);

            // Se envia la informacion al dialogo
            Long index = compra.get(jList2.getSelectedIndex());
            int num = accion.getNum(index);
            if(num == 0) {
                refresh();
                return;
            }

            // Se envia la informacion al dialogo
            oferta.setOferta(COMPRA, jList2.getSelectedValue().toString(), Integer.toString(num), Double.toString(accion.getMonto(index)), index);

            oferta.setVisible(true);
        } catch(Exception e) {
            new LoginWindow(properties).setVisible(true);
        }
    }//GEN-LAST:event_jList2MouseClicked

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:     
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void jMenu2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu2MouseClicked
        // TODO add your handling code here:
        EstadisticasDialog e = null;
        try{
            e = new EstadisticasDialog(this, false,this.properties);
        }catch(Exception ex){
            new LoginWindow(properties).setVisible(true);
        }
        e.setVisible(true);
    }//GEN-LAST:event_jMenu2MouseClicked

    private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1MouseClicked

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        NewOferta p = null;
        try{
        p = new NewOferta(this, true, VENTA, id, properties);
        }catch(Exception e){
            new LoginWindow(properties).setVisible(true);
        }
        p.setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        NewOferta p = null;
        try{
        p = new NewOferta(this, true, COMPRA, id, properties);
        }catch(Exception e){
            new LoginWindow(properties).setVisible(true);
        }
        p.setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenu3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu3MouseClicked
        // TODO add your handling code here:
        ConsultaWindow c = null;
        try{
        c = new ConsultaWindow(properties);
        consultlist.add(c);
        }catch(Exception e){
            int i;
            for(i=0;i<consultlist.size();i++){
                if((consultlist.get(i))!=null)
                    ((ConsultaWindow)(consultlist.get(i))).dispose();}
            this.dispose();
            new LoginWindow(properties).setVisible(true);
        }
        c.setVisible(true);
    }//GEN-LAST:event_jMenu3MouseClicked

    public void refresh() {
        try {
            compra = accion.getIdCompraInv(id);
            venta = accion.getIdVentaInv(id);
            ventaModel.clear();
            compraModel.clear();

            List<String> acciones = accion.obtenerCompraInv(id);
            for(String temp : acciones) {
                compraModel.addElement(temp);
            }
            acciones = accion.obtenerVentaInv(id);
            for(String temp : acciones) {
                ventaModel.addElement(temp);
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Se perdió conexión con el "
                    + "servidor", "Advertencia!!",
                    JOptionPane.INFORMATION_MESSAGE);
            new LoginWindow(properties).setVisible(true);
            this.dispose();
        }
    }

    private String id;
    // Arreglos que contienen las acciones del usuario
    private List<Long> compra;
    private List<Long> venta;

    private DefaultListModel ventaModel;
    private DefaultListModel compraModel;

    private Properties properties;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables

    private BeanAccionRemote lookupBeanAccionRemote(Properties properties) {
        try {
            Context c = new InitialContext(properties);
            return (BeanAccionRemote) c.lookup("java:comp/env/BeanAccion");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
